package com.abase.site.client;

import java.util.HashSet;

import com.abase.site.client.PocAbaseHistoryHandler.HistoryTokens;
import com.abase.site.client.events.LoginRequestEvent;
import com.abase.site.client.events.LoginRequestHandler;
import com.abase.site.client.events.LoginResponseEvent;
import com.abase.site.client.events.LoginResponseHandler;
import com.abase.site.client.open.widget.frontpage.FrontPageWidget;
import com.abase.site.client.open.widget.pagedetest.PageDeTestWidget;
import com.abase.site.client.prive.widget.login.AbaseLoginManager;
import com.abase.site.client.services.PocAbaseService;
import com.abase.site.client.services.PocAbaseServiceAsync;
import com.abase.site.client.widget.body.AbaseHomeBody;
import com.abase.site.client.widget.header.AbaseHeader;
import com.abase.site.shared.constants.AbaseConstants;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PocAbase implements EntryPoint, LoginRequestHandler, LoginResponseHandler, ValueChangeHandler<String> {
	
	private static final EventBus eventBus = new SimpleEventBus();
	
	private static AbaseLoginManager loginManager = null;
	
	private static PocAbaseServiceAsync abaseServiceAsync = null;

	
	private DialogBox loginDialogBox = null;
	
	/**
	 * bus d'event permettant de faire communiquer les widgets sans créer de dépendances
	 * @return
	 */
	public static EventBus getEventBus() {
		return eventBus;
	}
	public static AbaseLoginManager getLoginManager() {
		return loginManager;
	}
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		//
		// partie public
		//
		RootPanel.get().add(new AbaseHeader());
		
		final AbaseHomeBody home = new AbaseHomeBody();
		RootPanel.get().add(home);
		
		//
		//pour remplir le bandeau de gauche
		//
		//home.getLeft().add(widget1);
		//home.getLeft().add(widgetn);
		
		// 
		// on remplis la partie dynamic du milieu
		// le meme principe peut etre reproduit sur les parties droite et gauche
		// cette partie permet de pouvoir afficher le widget voulu grace au token
		FrontPageWidget frontPageWidget = null;
		try {
			frontPageWidget = new FrontPageWidget();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		home.addToDeck(new HashSet<String>() {
			
			private static final long serialVersionUID = 6797896545795797035L;

			{
				add(HistoryTokens.HOME_TOKEN.getValue());
				add("");
			}

		}, frontPageWidget);
		
		final PageDeTestWidget pageDeTestWidget = new PageDeTestWidget();
		home.addToDeck(new HashSet<String>() {
				private static final long serialVersionUID = -1286026680010643340L;
				{
					add(HistoryTokens.HISTORY_TEST_TOKEN.getValue());
				}
		}, pageDeTestWidget);
		
		
		//
		// pour remplir le bandeau de droite
		//
		//home.getRight().add(widget1);
		//home.getRight().add(widgetn);
		
		
		// ajouter un pied de page
		//RootPanel.get().add(footer);
		
		//
		// partie privee
		//
		
		//on reste a l ecoute d une demande d authentification
		loginManager = new AbaseLoginManager();
		eventBus.addHandler(LoginRequestEvent.TYPE, this);
		eventBus.addHandler(LoginResponseEvent.TYPE, this);
		
		History.addValueChangeHandler(new PocAbaseHistoryHandler());
		History.addValueChangeHandler(this);
	    History.fireCurrentHistoryState();
	    
	}

	@Override
	public void onLoginRequest(LoginRequestEvent event) {
		//TDOD token
		if (null == Cookies.getCookie(AbaseConstants.ABASEAUTH)) {
			this.loginDialogBox = new DialogBox();
			this.loginDialogBox.add(loginManager);
			this.loginDialogBox.setAnimationEnabled(true);
			this.loginDialogBox.setGlassEnabled(true);
			RootPanel.get().add(this.loginDialogBox);
			this.loginDialogBox.center();
			this.loginDialogBox.show();
		} else {
			loginManager.doLogin(true);
		}
		
	}

	@Override
	public void onLoginResponse(LoginResponseEvent event) {
		if (null == event.getContext().getProfile()) {
			// la demande de login a ete annuler
			this.closeLoginPopup();
		} else {
			this.closeLoginPopup();
			//TODO take full history token and manage history
		}
	}
	
	public static PocAbaseServiceAsync getAbaseServices() {
		if (null != abaseServiceAsync) {
			return abaseServiceAsync;
		}
		
		abaseServiceAsync = (PocAbaseServiceAsync) GWT.create(PocAbaseService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) abaseServiceAsync;
		endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "authentification");
		return abaseServiceAsync;
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		if (token.startsWith(HistoryTokens.PRIVATE_HOME_TOKEN.getValue())) {
			closeLoginPopup();
			LoginRequestEvent requestEvent = new LoginRequestEvent();
			//TODO make context in LoginRequestEvent and send the full token
			eventBus.fireEvent(requestEvent);
		}
		if (token.equals(HistoryTokens.PRIVATE_HOME_TOKEN.getValue())) {
			//TODO private history
		}
		
	}
	
	private void closeLoginPopup() {
		if (this.loginDialogBox.isShowing()) {
			this.loginDialogBox.hide();
			RootPanel.get().remove(this.loginDialogBox);
		}
	}
}
